package xdu.lz.netty.g_handler.tcp_粘包;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @Author Badribbit
 * @create 2019/4/14 21:47
 */

/**
 * TCP粘包
 */
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count = 0;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte [] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        String message = new String(bytes,"utf-8");
        System.out.println("服务端收到的消息是 : "+ message);
        System.out.println("服务端已经收到的消息数量"+(++this.count));

        ByteBuf byteBuf =
                Unpooled.copiedBuffer(UUID.randomUUID().toString(), Charset.forName("utf8"));
        ctx.writeAndFlush(byteBuf);

    }
    //异常的捕获，一般出现异常，就把连接关闭
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
